using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interactivity;

namespace ScrobbleItSL.Utils.Behaviors
{
    public class UpdateOnTextChangedBehavior : Behavior<TextBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.TextChanged += AssociatedObjectOnTextChanged;
        }

        private void AssociatedObjectOnTextChanged( object sender, TextChangedEventArgs textChangedEventArgs )
        {
            BindingExpression binding = this.AssociatedObject.GetBindingExpression( TextBox.TextProperty );
            if ( binding != null ) 
                binding.UpdateSource();
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.TextChanged -= AssociatedObjectOnTextChanged;
        }
    }
}
